//
//  YHNavigationController.swift
//  YHSwiftProject
//
//  Created by LYH on 2018/11/2.
//  Copyright © 2018年 LYH. All rights reserved.
//

import UIKit

class YHNavigationController: UINavigationController ,UINavigationControllerDelegate{

    var popDelegate:UIGestureRecognizerDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
     self.popDelegate = self.interactivePopGestureRecognizer?.delegate
        self.delegate = self
    }
    
    //MARK: - UIGestureRecognizerDelegate代理
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        
        //实现滑动返回的功能
        //清空滑动返回手势的代理就可以实现
        if viewController == self.viewControllers[0] {
            
            self.interactivePopGestureRecognizer?.delegate = self.popDelegate
            
        } else {
            
            self.interactivePopGestureRecognizer?.delegate = nil;
        }
    }
    
    //拦截跳转
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if self.viewControllers.count>0 {
           viewController.hidesBottomBarWhenPushed = true
//            //添加图片
//            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "navbar_icon_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(backClick))
//            //添加文字
//            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: #selector(backClick))
            //跳转后隐藏tabbar
            let leftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 44))
            leftButton.setTitle("返回", for: .normal)
            leftButton.setTitleColor(.white, for: .normal)
            leftButton.setImage(UIImage.init(named: "navbar_icon_back"), for: .normal)
            leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            leftButton.addTarget(self, action: #selector(backClick), for: .touchUpInside)
            //添加按钮
           viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftButton)
          
//            滑动返回失效
//            self.interactivePopGestureRecognizer?.isEnabled = self.viewControllers.count > 1
//            self.interactivePopGestureRecognizer?.delegate = self as? UIGestureRecognizerDelegate;
            
        }
        super.pushViewController(viewController, animated: true)
    }
    
    //@objc前缀 事件响应
    @objc func backClick() -> Void {

        if self.presentationController != nil && self.children.count == 0{
            self.dismiss(animated: true) {

            }
        }else
        {
            self.popViewController(animated: true)
        }
    }
}
